<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 表单元素组合
//+---------------------------------------------------------------------------------------------------------------------


namespace helper\form;

/**
 * form元素集合类
 * @package helper\form
 */
class Form
{
	/**
	 * 生成输入框
	 * @param $data
	 */
	static function text( $data )
	{
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<input type="text" class="layui-input" name="{$data['key']}" value="{$data['value']}">
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;
	}

	/**
	 * 生成密码框
	 * @param $data
	 * @return string
	 */
	static function password( $data )
	{
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<input type="password" class="layui-input" name="{$data['key']}" value="{$data['value']}">
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;
	}

	/**
	 * 生成密码框
	 * @param $data
	 * @return string
	 */
	static function number( $data )
	{
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<input type="number" class="layui-input" name="{$data['key']}" value="{$data['value']}">
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;
	}

	/**
	 * 生成文本域
	 * @param $data
	 */
	static function textarea( $data )
	{
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<textarea name="{$data['key']}" class="layui-textarea">{$data['value']}</textarea>
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;

	}

	/**
	 * 生成开关
	 * @param $data
	 * @return string
	 */
	static function switch( $data )
	{
		$checkd = '';
		if ($data['value'] == 'on') {
			$checkd = 'checked';
		}
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<input type="checkbox" name="{$data['key']}" lay-skin="switch" lay-filter="{$data['key']}" lay-text="{$data['option']}" $checkd>
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;
	}

	/**
	 * 生成隐藏input
	 * @param $data
	 * @return string
	 */
	static function hidden( $data )
	{
		return <<<EOF
<div class="layui-form-item">
<label for="" class="layui-form-label">{$data['title']}</label>
<div class="layui-input-block">
<input type="hidden" class="layui-input" name="{$data['key']}" value="{$data['value']}">
</div>
<div class="layui-input-block j-form-tips">
{$data['tips']}
</div>
</div>
EOF;
	}

	/**
	 * 生成下拉框
	 * @param $data
	 * @return string
	 */
	static function select( $data )
	{
		$options = explode("\n", $data['option']);
		$selected = '';
		$html = '<div class="layui-form-item">
                    <label for="" class="layui-form-label">' . $data['title'] . '</label>
                    <div class="layui-input-inline">
                    <select name="' . $data['key'] . '" lay-filter="' . $data['key'] . '">
                    <option></option>';
		foreach ($options as $key => $value){
			if (strpos($value, ':') !== false) {
				$op = explode(':', $value);
				$selected = $op[0] == $data['value'] ? 'selected' : '';
				$html .= '<option value="' . $op[0] . '" ' . $selected . '>' . $op[1] . '</option>';
			} else{
				$selected = $key == $data['value'] ? 'selected' : '';
				$html .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
			}
		}
		$html .= '</select></div><div class="layui-input-inline j-form-tips">' . $data['tips'] . '</div></div>';
		return $html;
	}

	/**
	 * 生成单选框
	 * @param $data
	 * @return string
	 */
	static function radio( $data )
	{
		$options = explode("\n", $data['option']);
		$checked = '';
		$html = '<div class="layui-form-item">
                    <label for="" class="layui-form-label">' . $data['title'] . '</label>
                    <div class="layui-input-block">';
		foreach ($options as $key => $value){
			if (strpos($value, ':') !== false) {
				$op = explode(':', $value);
				$checked = $op[0] == $data['value'] ? 'checked' : '';
				$html .= '<input type="radio" lay-filter="' . $data['key'] . '" name="' . $data['key'] . '" value="' . $op[0] . '" title="' . $op[1] . '" ' . $checked . '>';
			} else{
				$checked = $key == $data['value'] ? 'checked' : '';
				$html .= '<input type="radio" lay-filter="' . $data['key'] . '"  name="' . $data['key'] . '" value="' . $key . '" title="' . $value . '" ' . $checked . '>';
			}
		}
		$html .= '</div><div class="layui-input-block j-form-tips">' . $data['tips'] . '</div></div>';
		return $html;
	}

	/**
	 * 生成复选框
	 * @param $data
	 * @return string
	 */
	static function checkbox( $data )
	{
		$options = explode("\n", $data['option']);
		$checked = '';
		$html = '<div class="layui-form-item">
                    <label for="" class="layui-form-label">' . $data['title'] . '</label>
                    <div class="layui-input-block">';
		foreach ($options as $key => $value){
			if (strpos($value, ':') !== false) {
				$op = explode(':', $value);
				$checked = ($op[0] == $data['value'] || in_array($op[0], explode(',', $data['value']))) ? 'checked' : '';
				$html .= '<input type="checkbox" lay-filter="' . $data['key'] . '" name="' . $data['key'] . '[]" value="' . $op[0] . '" title="' . $op[1] . '" ' . $checked . ' lay-skin="primary" >';
			} else{
				$checked = $key == $data['value'] ? 'checked' : '';
				$html .= '<input type="checkbox" lay-filter="' . $data['key'] . '"  name="' . $data['key'] . '[]" value="' . $key . '" title="' . $value . '" ' . $checked . ' lay-skin="primary" >';
			}
		}
		$html .= '</div><div class="layui-input-block j-form-tips">' . $data['tips'] . '</div></div>';
		return $html;
	}

	/**
	 * 生成文件域
	 * @param $data
	 * @return string
	 */
	static function image( $data )
	{
		$value = $prewImg = '';
		if (!empty($data['value'])) {
			$value = get_file_path($data['value']);
			$prewImg = '<img src="' . $value . '" class="j-img-preview-item" ondblclick="removePreviewImg(this)">';
		}

		return <<<EOF
<div class="layui-form-item">
                <label for="" class="layui-form-label">{$data['title']}</label>
                <div class="layui-input-block j-upload">
                   <a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-sm j-upload-dom">
                       <input type="file" 
                           name="{$data['key']}" 
                           id="upload_{$data['key']}"
                           class="j-file" 
                           onchange="upload_{$data['key']}(event,this)" 
                           accept="image/*"
                       />
                       <input type="text" class="j-upload-input" readonly value="{$value}"/>
                       <input type="hidden" class="j-upload-input" readonly value="{$data['value']}" name="{$data['key']}file"/>
                       <i class="layui-icon layui-icon-upload"></i>选择文件</a>
                </div>
                <div class="j-img-preview-{$data['key']}">
                {$prewImg}
                </div>

                <div class="layui-input-block j-form-tips">{$data['tips']}，双击可删除</div>
                <script>
                function upload_{$data['key']}(event,e){
                    var file = event.target.files[0]
                        , preview = document.querySelector('.j-img-preview-{$data['key']}')
                        , reader = new FileReader();
                    if(!file){
                        layui.layer.msg('请选择文件');
                    }else{
                        $(e).next().val($(e).val())
    
                        reader.addEventListener("load", function () {
							if(preview.children.length >= 1){
							preview.innerHTML = '';
							}
							var image = new Image();
							image.title = file.name;
							image.src = this.result;
							image.classList.add('j-img-preview-item');
							image.ondblclick = function(e){
							    $(e.currentTarget).parent().prev().find('input[type=text]').val('')
                                $(e.currentTarget).parent().prev().find('input[type=hidden]').val('')
							    $(e.currentTarget).remove();
							}
                            
                            preview.append( image );
                        }, false);
    
                        reader.readAsDataURL(file);    
                    }
                }
            </script>
            </div>
            
EOF;
	}

	/**
	 * 生成文件域
	 * @param $data
	 * @return string
	 */
	static function images( $data )
	{
		$prewImg = '';
		$imgs = [];
		if (isJson($data['value'])) {
			$imgs = json_decode($data['value'], true);
		} else if (strpos($data['value'], ',') !== false) {
			$imgs = explode(',', $data['value']);
		}
		$value = '';
		foreach ($imgs ?? [] as $img){
			$value .= get_file_path($img);
			$prewImg .= '<img src="' . get_file_path($img) . '" class="j-img-preview-item" ondblclick="removePreviewImg(this)">';
		}
		return <<<EOF
<div class="layui-form-item">
                <label for="" class="layui-form-label">{$data['title']}</label>
                <div class="layui-input-block j-upload">
                   <a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-sm j-upload-dom">
                       <input type="file" 
                           name="{$data['key']}[]" 
                           id="upload_file_{$data['key']}"
                           class="j-file" 
                           onchange="upload_{$data['key']}(event,this)" 
                           accept="image/*"
                           multiple="multiple"
                       />
                       <input type="text" class="j-upload-input" readonly value="{$value}"/>
                       <input type="hidden" class="j-upload-input" readonly value="{$data['value']}" name="{$data['key']}file"/>
                       <i class="layui-icon layui-icon-upload"></i>选择文件</a>
                </div>
                <div class="j-img-preview-{$data['key']}">
                $prewImg
                </div>

                <div class="layui-input-block j-form-tips">{$data['tips']}，双击可删除</div>
                <script>
               
                function upload_{$data['key']}(event,e){
                    var files = event.target.files
                        , preview = document.querySelector('.j-img-preview-{$data['key']}');
                    if($(preview).children().length > 0){
                        $(preview).children().remove();
                    }
                    if (files) {
                        $.each(files,function(index,file){
                            let reader = new FileReader()
                            reader.addEventListener("load", function (ee) {
                                
                                var image = new Image();
                                image.title = file.name;
                                image.src = this.result;
                                image.classList.add('j-img-preview-item');
                                image.ondblclick = function(e){
								    $(e.currentTarget).parent().prev().find('input[type=text]').val('')
								    $(e.currentTarget).parent().prev().find('input[type=hidden]').val('')
								    $(e.currentTarget).remove();
								}
                                preview.append( image );
                            }, false);
        
                            reader.readAsDataURL(file);    
                        })
                      }
                    
                    $(e).next().val($(e).val())
    
                            
                }
                    
            </script>
            </div>
            
EOF;
	}

	/**
	 * 文件域
	 * @param $data
	 * @return string
	 */
	static function file( $data )
	{
		$value = get_file((int)$data['value']);
		if(empty($value)){
		    $value = ['path'=>'','name'=>''];
        }
		$html =  <<<EOF
<div class="layui-form-item">
                <label for="" class="layui-form-label">{$data['title']}</label>
                <div class="layui-input-block j-upload">
                   <a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-sm j-upload-dom">
                       <input type="file" 
                           name="{$data['key']}" 
                           id="upload_{$data['key']}"
                           class="j-file" 
                           onchange="upload_{$data['key']}(event,this)" 
                       />
                      <input type="text" class="j-upload-input" readonly value="{$value['path']}"/>
                       <input type="hidden" class="j-upload-input" readonly value="{$data['value']}" name="{$data['key']}file"/>
                       <i class="layui-icon layui-icon-upload"></i>选择文件</a>
                </div>
                <div class="j-img-preview j-img-preview-{$data['key']}">
EOF;
		if(!empty($value['path'])){
            $html .= <<<EOF
                    <div>
                        <ul>
                            <li><img title="1.csv" src="/static/common/img/admin/file.png" class="j-img-preview-item"></li>
                            <li>{$value['name']}</li>
                        </ul>
                        <div class="clear ">
                        </div>
                    </div>
EOF;
        }

                $html .= <<<EOF
</div>

                <div class="layui-input-block j-form-tips">{$data['tips']}，双击可删除</div>
                <script>
                function upload_{$data['key']}(event,e){
                    var file = event.target.files[0]
                        , preview = document.querySelector('.j-img-preview-{$data['key']}')
                        , reader = new FileReader();
                    if(!file){
                        layui.layer.msg('请选择文件');
                    }else{
                        $(e).next().val($(e).val())
                        reader.addEventListener("load", function () {
                            if(preview.children.length >= 1){
                                preview.innerHTML = '';
                            }
                    
                            var image = new Image();
                            image.title = file.name;
                            if(file.type.split('/').shift() == 'image'){
                                image.src=this.result;                            
                            }else{
                                image.src = '/static/common/img/admin/file.png';
                            }
                            image.classList.add('j-img-preview-item');
                            image.ondblclick = function(e){
							    $(e.currentTarget).parent().prev().find('input[type=text]').val('')
                                $(e.currentTarget).parent().prev().find('input[type=hidden]').val('')
							    $(e.currentTarget).remove();
							}
							
                            let div = document.createElement('div');
                            div.innerHTML = '<ul><li></li><li>'+ file.name+'</li></ul>';
                            div.onmouseover = function (e){
                                $(this).children('.clear').show();
                            }
                            div.onmouseout = function(e) {
                                $(this).children('.clear').hide();
                            }
                            
                            //clear遮罩层
                            let clearElement = document.createElement('div');
                            $(clearElement).addClass('clear');
                            clearElement.onclick=function(clear){
                                //文件删除
                                $(e).val('') ;
                                $(e).next().val('');
                                $(clear.target).parent('div').remove();
                            }
                            
                            $(div).append(clearElement);
                            $(div).find('li').eq(0).append(image);
                            preview.append( div );
                        }, false);
                        reader.readAsDataURL(file);    
                    }
                }
            </script>
            </div>
            
EOF;
		return $html;
	}

	/**
	 * 文件域
	 * @param $data
	 * @return string
	 */
	static function files( $data )
	{
		if (!empty($data['value'])) {
			$value = join(',', get_file_path($data['value']));
		} else{
			$value = '';
		}
		return <<<EOF
<div class="layui-form-item">
                <label for="" class="layui-form-label">{$data['title']}</label>
                <div class="layui-input-block j-upload">
                   <a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-sm j-upload-dom">
                       <input type="file" 
                           name="{$data['key']}[]" 
                           id="upload_{$data['key']}"
                           class="j-file" 
                           onchange="upload_{$data['key']}(event,this)" 
                           multiple="multiple"
                       />
                      <input type="text" class="j-upload-input" readonly value="{$value}"/>
                       <input type="hidden" class="j-upload-input" readonly value="{$data['value']}" name="{$data['key']}file"/>
                       <i class="layui-icon layui-icon-upload"></i>选择文件</a>
                </div>
                <div class="j-img-preview j-img-preview-{$data['key']}">
                </div>

                <div class="layui-input-block j-form-tips">{$data['tips']}，双击可删除</div>
                <script>
                function upload_{$data['key']}(event,e){
                    var files = event.target.files
                        , preview = document.querySelector('.j-img-preview-{$data['key']}');
                    console.log(files);
                    if(!files){
                        layui.layer.msg('请选择文件');
                    }else{
                        $.each(files,function(index,file){
                            let reader = new FileReader();
                           $(e).next().val($(e).next().val()+file.name+',');
                            reader.addEventListener("load", function () {
                               
                        
                                var image = new Image();
                                image.title = file.name;
                                if(file.type.split('/').shift() == 'image'){
                                    image.src=this.result;                            
                                }else{
                                    image.src = '/static/common/img/admin/file.png';
                                }
                                image.classList.add('j-img-preview-item');
                                image.ondblclick = function(e){
                                    $(e.currentTarget).parent().prev().find('input[type=text]').val('')
                                    $(e.currentTarget).parent().prev().find('input[type=hidden]').val('')
                                    $(e.currentTarget).remove();
                                }
                                
                                let div = document.createElement('div');
                                div.innerHTML = '<ul><li></li><li style="text-align:center;">'+ file.name+'</li></ul>';
                                div.onmouseover = function (e){
                                    $(this).children('.clear').show();
                                }
                                div.onmouseout = function(e) {
                                    $(this).children('.clear').hide();
                                }
                                
                                //clear遮罩层
                                let clearElement = document.createElement('div');
                                $(clearElement).addClass('clear');
                                clearElement.onclick=function(clear){
                                    files = Array.prototype.slice.call(files);
                                    //文件删除
                                    files.splice(index,1)
                                    console.log(files);
                                    $(e).val(files);
                                    $(clear.target).parent('div').eq(index).remove();
                                }
                                
                                $(div).append(clearElement);
                                $(div).find('li').eq(0).append(image);
                                preview.append( div );
                            }, false);
                            reader.readAsDataURL(file); 
                        })
                         
                    }
                }
            </script>
            </div>
            
EOF;
	}

	static function ueditor( $data )
	{
		return <<<EOF
 <div class="layui-form-item">
 		<label for="" class="layui-form-label">{$data['title']}</label>
        <div class="layui-input-block" style="width:80%;">
            <script id="container_{$data['key']}" name="{$data['key']}" type="text/plain">{$data['value']}</script>
        </div>
        <div class="layui-input-block j-form-tips">{$data['tips']}</div></div>
          <script type="text/javascript">
            var {$data['key']};
		    $(document).ready(function(){
		        {$data['key']} = UE.getEditor('container_{$data['key']}');
		    })
	    </script>
    </div>

EOF;

	}

	static function color( $data )
	{
		return <<<EOF
 <div class="layui-form-item">
        <label for="" class="layui-form-label">{$data['title']}</label>
        <div class="layui-input-inline">
            <input type="text" name="{$data['key']}" value="{$data['value']}" class="layui-input" placeholder="请输入颜色"  readonly>
        </div>
        <div class="layui-input-inline">
            <input type="color" value="{$data['value']}"class="layui-input j-input-color" onfocus="focusColor(this)" onchange="checkedColor(this)">
        </div>
        <div class="layui-input-inline j-form-tips">{$data['tips']}</div>
    </div>
EOF;

	}

	static function mditor( $data )
	{
		return <<<MDITOR
 <div class="layui-form-item">
        <label for="" class="layui-form-label">{$data['title']}</label>
        <div class="layui-input-block">
            <textarea name="{$data['key']}" id="{$data['key']}" cols="30" rows="10">{$data['value']}</textarea>
        </div>
        <div class="layui-input-block j-form-tips">{$data['tips']}</div>
        <script>
        var {$data['key']};
		 $(document).ready(function(){
		        {$data['key']} = new mditor(document.getElementById('{$data['key']}'));
		    })
		</script>
    </div>

MDITOR;

	}
}